import React from 'react';
import moment from 'moment';

import * as style from './DateRangePicker.less';

import DatePicker from 'material-ui/lib/date-picker/date-picker';

const datePickerStyle = {
	width: 120,
	marginLeft: 10,
	marginRight: 10
}

export default class DateRangePicker extends React.Component {
	static propTypes = {
	  	onDateRangeChange: React.PropTypes.func,
	  	startDate: React.PropTypes.string,
	  	endDate: React.PropTypes.string
	};

	static defaultProps = {
		onDateRangeChange: function() {},
	};

	state = {
		startDate: new Date,
		endDate: new Date
	};

	constructor(props) {
		super(props);
	}

	componentDidMount() {
		let { startDate, endDate } = this.props;

		this.setState({
			startDate: moment(startDate).toDate(),
			endDate: moment(endDate).toDate()
		});
	}

	// 格式化处理选择的日期
	handleFormatDate = (date) => {
		let { fmt = 'YYYY-MM-DD' } = this.props;
		return moment(date).format(fmt);
	};

	// 开始日期变化
	handleStartDateChange = (date) => {
		this.setState({ startDate: date });
		this.notifyDateRangeChange();
	};

	// 结束日期变化
	handleEndDateChange = (date) => {
		this.setState({ endDate: date });
		this.notifyDateRangeChange();
	};

	// 通知日期范围发生变化
	notifyDateRangeChange = () => {
		let { onDateRangeChange } = this.props;
		let { startDate, endDate } = this.state;
		setTimeout(() => {
			onDateRangeChange(startDate, endDate);
		}, 0);
	};

	render() {
		let { startDate, endDate } = this.state;

		return (
			<div className={style.dateRangePicker}>
				<DatePicker 
					textFieldStyle={datePickerStyle} 
					onChange={(nil, date) => this.handleStartDateChange(date) } 
					hintText="开始日期" 
					mode="landscape" 
					formatDate={this.handleFormatDate} 
					value={startDate}
					autoOk={true} />
				<span>至</span>
				<DatePicker 
					textFieldStyle={datePickerStyle} 
					onChange={(nil, date) => this.handleEndDateChange(date) } 
					hintText="结束日期" 
					mode="landscape" 
					formatDate={this.handleFormatDate} 
					value={endDate}
					autoOk={true} />
			</div>
		);
	}
}